package ru.ifmo.rybakov.muclumon;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PropertyServlet extends HttpServlet {

	private static final long serialVersionUID = 8690519305085078011L;
	
	private static final Logger logger = LoggerFactory.getLogger(PropertyServlet.class);

//	/* (non-Javadoc)
//	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
//	 */
//	@SuppressWarnings("unchecked")
//	@Override
//	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
//			throws ServletException, IOException {
//		// TODO Auto-generated method stub
////		super.doGet(req, resp);
//		String idString = req.getParameter("id");
//		Integer id = Integer.valueOf(idString);
//		
//		EntityManager em = Database.getEntityManagerFactory().createEntityManager();
//		try {
//			Revision revision = em.find(Revision.class, id);
//			Query query = em.createQuery("SELECT e FROM Element e WHERE e.revision = :revision");
//			query.setParameter("revision", revision);
//			List<Element> elements = query.getResultList();
//			req.setAttribute("elements", elements);
//			req.getRequestDispatcher("/revision/index.jsp").forward(req, resp);
//		} finally {
//			em.close();
//		}
//	}

	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String action = request.getParameter("action");
		if ("remove".equals(action)) {
			String idString = request.getParameter("id");
			Integer id = Integer.valueOf(idString);
			logger.debug("Removing property {}", id);
			EntityManager em = Database.getEntityManagerFactory().createEntityManager();
			try {
				EntityTransaction t = em.getTransaction();
				try {
					t.begin();
					PropertyValue pv = em.find(PropertyValue.class, id);
					Revision revision = pv.getElement().getRevision();
					if (pv != null) {
						em.remove(pv);
						logger.info("Property {} removed for revision {}", new Object[] { id, revision.getId() });
					} else {
						logger.warn("No property {} to be removed", id);
					}
					t.commit();
					
					Query query = em.createQuery("SELECT e FROM Element e WHERE e.revision = :revision");
					query.setParameter("revision", revision);
					List<Element> elements = query.getResultList();
					request.setAttribute("elements", elements);
					
					query = em.createQuery("SELECT p FROM Property p");
					request.setAttribute("properties", query.getResultList());
					
					request.getRequestDispatcher("/revision/index.jsp").forward(request, response);
				} finally {
					if (t.isActive()) {
						t.rollback();
					}
				}
			} finally {
				em.close();
			}
		} else if ("add".equals(action)) {
			String idString = request.getParameter("id");
			Integer id = Integer.valueOf(idString);
			
			String name = request.getParameter("name");
			String value = request.getParameter("value");
			
			logger.debug("Adding property (name='{}', value='{}') to element {}", new Object[] { name, value, id });
			PropertyValue propertyValue = PropertyValueFactory.create(name, value);
			EntityManager em = Database.getEntityManagerFactory().createEntityManager();
			try {
				EntityTransaction t = em.getTransaction();
				try {
					t.begin();
					Element element = em.find(Element.class, id);
					element.addPropertyValue(propertyValue);
					t.commit();
					
					Query query = em.createQuery("SELECT e FROM Element e WHERE e.revision = :revision");
					query.setParameter("revision", element.getRevision());
					List<Element> elements = query.getResultList();
					request.setAttribute("elements", elements);
					
					query = em.createQuery("SELECT p FROM Property p");
					request.setAttribute("properties", query.getResultList());
					
					request.getRequestDispatcher("/revision/index.jsp").forward(request, response);
				} finally {
					if (t.isActive()) {
						t.rollback();
					}
				}
			} finally {
				em.close();
			}
		} else {
			super.doPost(request, response);
		}
		
		// TODO Auto-generated method stub
		
	}
}
